import React, { useEffect, useMemo, useState } from "react";
import { SideBar, Toast } from "antd-mobile";
import NavBar from "@/components/NavBar/NavBar";
import SearchBar from "@/components/SearchBar/SearchBar";
import { fetchCategoryListThunk } from "@/store/modules/categoryStore";
import { useEnhanceDispatch, useEnhanceSelector } from "@/hooks";
import type { Category as CategoryType } from "@/type/CategoryType";
import { useNavigate } from "react-router-dom";
import "./Category.scss";

const Category: React.FunctionComponent = () => {
   const navigate = useNavigate();
   const enhanceDispatch = useEnhanceDispatch();

   // 分类列表
   const categoryList: CategoryType[] = useEnhanceSelector(state => state.categoryStore.categoryList);
   // 当前激活项
   const [activeKey, setActiveKey] = useState<number>(0);
   // 根据当前激活项ID计算出当前所属分类的对象
   const subCategory: CategoryType = useMemo(() => categoryList.find(item => item.category_id === activeKey), [activeKey]) as CategoryType;

   /**
    * @description 获取分类列表的回调函数
    * */
   const fetchCategoryList = async () => {
      try {
         const categoryList: CategoryType[] = await enhanceDispatch(fetchCategoryListThunk()).unwrap();
         setActiveKey(categoryList[0].category_id);
      } catch (rejectedValueOrSerializedError: any) {
         Toast.show(rejectedValueOrSerializedError);
      }
   };

   /**
    * @description 切换面板的回调回调
    * */
   const changeActiveKey = (activeKey: string) => {
      setActiveKey(Number(activeKey));
   };

   /**
    * @description 跳转搜索页面的回调函数
    * */
   const goToSearch = () => {
      navigate("/search");
   };

   useEffect(() => {
      fetchCategoryList();
   }, []);

   return (
      <div className="category-container">
         {/*头部*/}
         <div className="header">
            <NavBar children="全部分类"></NavBar>
            <SearchBar placeholder="搜索你要找的商品" onClick={goToSearch}></SearchBar>
         </div>
         {/*主体*/}
         <div className="main">
            {/*分类侧边栏*/}
            <div className="left">
               <SideBar activeKey={activeKey + ""} onChange={changeActiveKey}>
                  {categoryList?.map((item, index) => (
                     <SideBar.Item title={item.name} key={item.category_id}></SideBar.Item>))}
               </SideBar>
            </div>
            {/*分类列表*/}
            <div className="right">
               {
                  subCategory?.children?.map(item => {
                     return (
                        <div className="category-item" key={item.category_id} onClick={()=>navigate(`/good-list?categoryId=${item.category_id}`)}>
                           <img src={item.image.external_url} alt="" />
                           <span>{item.name}</span>
                        </div>
                     );
                  })
               }
            </div>
         </div>
      </div>
   );
};

export default Category;
